package com.chc.util;

import java.io.IOException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


public class JsonUtil {
	
	private static final Map<String, Class> classMap = new HashMap<String, Class>();
	
	static {
//		classMap.put("person", AgTrack.class);
	}
	
	public static Object buildObject(String type, LinkedHashMap<String, Object> map) {
		Class cls = classMap.get(type);
		if(cls == null)
			throw new RuntimeException(String.format("name %s not regist", type));
		
		Object ins = null;
		try {
			ins = cls.newInstance();
		} catch (Exception e1) {
			throw new RuntimeException(String.format("%s new instanse fail", cls), e1);
		}
		
		Method[] ms = cls.getMethods();
		for(Method m : ms) {
			String mName = m.getName();
			if(mName.startsWith("set") && mName.length() > 3 && m.getParameterTypes().length == 1) {
				String vName = mName.substring(3);
				if(vName.length() > 1) {
					vName = vName.substring(0, 1).toLowerCase() + vName.substring(1);
				} else {
					vName = vName.toLowerCase();
				}
				
				Class pType = m.getParameterTypes()[0];
				if(map.get(vName) != null) {
					Class vType = map.get(vName).getClass();
					if(vType != pType) {
						if((pType == int.class || pType == Integer.class || pType == long.class || pType == Long.class)
								&& vType == Integer.class) {
							try {
								m.invoke(ins, ((Integer)map.get(vName)).intValue());
								continue;
							} catch (Exception e) {
								throw new RuntimeException(String.format("Invock method %s fail", mName), e);
							}
						}
						
						if(pType == Date.class) {
							long times = -1;
							if(vType == Integer.class) {
								times = Integer.valueOf((Integer)map.get(vName));
							} else {
								times = (Long) map.get(vName);
							}
							
							try {
								m.invoke(ins, new Date(times));	
							} catch(Exception e) {
								throw new RuntimeException(String.format("Invock method %s fail", mName), e);
							}
						}
					} else {
						try {
							m.invoke(ins, pType.cast(map.get(vName)));
						} catch (Exception e) {
							throw new RuntimeException(String.format("Invock method %s fail", mName), e);
						}
					}
				}
			}
		}
		
		return ins;
	}
}
